/**
 * Created by wtuser on 2016/10/18.
 */

//先执行指令--->service----->(业务controller)----->controller---->link

angular.module('wtmapModule', ["template/map.html"])
    .service('wtmapService', ['$rootScope', '$q', '$filter', function($rootScope, $q, $filter){


        var maps = [];

        dojo.registerModulePath("wt", "/lib/modules/wt-map");
        //dojo.require("mapPath.application.Map");

        var config = {
            //mapDivId : mapid,
            layerInfo : [],
            geoBasemap : $rootScope.arcgisConfig.geoBasemap,
            arcgisServer : $rootScope.arcgisConfig.arcgisServer
        };

        if($rootScope.arcgisConfig.geoCenter)
            config.centerLngLat = $rootScope.arcgisConfig.geoCenter.split(",");


        //转换配置的图层成数组
        if($rootScope.arcgisConfig.layerInfos){
            var arrs = $rootScope.arcgisConfig.layerInfos.split(";");
            $.each(arrs, function(index, value){
                var lyrs = value.split(":");
                if(lyrs.length == 2){
                    config.layerInfo.push({layerName : lyrs[0], serverId : lyrs[1]});
                }
            });
        }
        ;

        /**
         * 初始化地图
         * @param mapid 地图控件div
         * @param showbasemap 是否显示高的底图
         * @param spatialfeference 参考坐标系
         * @param lods 地图自定义级别 可为空
         * @returns {Promise}  延迟返回地图接口操作对象
         */
        this.intialMap = function(mapid, showbasemap, spatialfeference, lods){

            var mapobj = this.getMap(mapid);

            var defer = $q.defer();  //声明延后执行
            require(["wt/application.Map"], function(mapApp){
                config.mapDivId = mapid;
                config.lods = lods;
                config.spatialReference = spatialfeference;

                var globalMap = new mapApp(config);
                if(mapobj){
                    $.each(maps, function(index, item){
                        if(item && item.id == mapid){
                            maps.splice(index, 1); //移除
                        }
                    });
                }

                maps.push({id : mapid, mapObj : globalMap});

                defer.resolve(globalMap);  //声明执行成功
                if(showbasemap){
                    //高德底图
                    globalMap.addGaodeLayer(config.geoBasemap, mapid + "basemapToggleDiv");
                }

                globalMap.addDynamicMap($rootScope.arcgisConfig.baseMap);


                globalMap.zoomTobyXY(477419.175, 2816742.538, 13);
            });
            return defer.promise; //返回承诺，返回获取数据的API

        }


        //获取地图实例对象操作接口
        this.getMap = function(mapid){
            var map = $filter('filter')(maps, {'id' : mapid});
            if(map && map.length > 0){
                return map[0].mapObj;
            }
            else return null;
        }

    }])
    .controller('wtmapController', ['$rootScope', '$scope', function($rootScope, $scope){

        $scope.intial = function(mapid, mapIntialed){

        }

    }])
    .directive('wtMap', function(){

        var ctrl = {
            restrict : 'EA',
            replace : true,
            //template: "<div id=\"{{ mapid }}\" style='border:0;position:relative;height:{{ divheight }}px'> <div class='basemapToggleDiv' id='{{ basemapToggleDiv }}'   > </div>",
            templateUrl : 'template/map.html',
            scope : {
                divheight : '=height',  //与外界数据传递
                showbasemap : '=showgdmap',
                mapIntialed : '&',      //使用Intialed回调是为了保证地图id已绑定值
                mapinstance : '=mapinstance',
                mapid : '@'
            },
            require : 'wtMap', //引入控制器时需要
            controller : 'wtmapController',
            link : function(scope, element, attrs, controller){ //控件内部一系列操作实现

                if(!scope.mapid)
                    scope.mapid = "map1";
                scope.basemapToggleDiv = scope.mapid + "basemapToggleDiv";

                $($(element[0]).context.children[0]).attr('id',scope.basemapToggleDiv);
                $(element[0]).height(scope.divheight);
                //通过观察id属性变化时回调执行，如不观察id属性，有可能找不到id值。
                attrs.$observe('id', function(newValue){
                    if(scope.mapIntialed && typeof (scope.mapIntialed) == "function")
                        scope.mapIntialed();

                });

            }
        };

        return ctrl;
    });

angular.module("template/map.html", []).run(["$templateCache", function($templateCache){
    $templateCache.put("template/map.html",
        "<div id=\"{{ mapid }}\" nt-style=\"{ border:0,position:relative,height: divheight }\"> <div class='basemapToggleDiv'  > </div>"
    );
}]);